package com.pkk.spring.cloud.service.rpc.result;

import com.pkk.spring.cloud.service.rpc.code.StatusCode;
import com.pkk.spring.cloud.service.rpc.code.system.SystemCode;
import com.pkk.spring.cloud.service.rpc.response.ResponseBody;
import com.pkk.spring.cloud.service.rpc.response.ResponseHeader;
import java.util.Optional;

/**
 * 响应工具类
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-01-06 15:01
 **/
public class R {


  public static <T> ResponseBody<T> success() {
    return success(null);
  }

  public static <T> ResponseBody<T> success(T t) {
    return successMessage(null, t);
  }

  public static <T> ResponseBody<T> successMessage(String message) {
    return successMessage(message, null);
  }

  public static <T> ResponseBody<T> successMessage(String message, T t) {
    return new ResponseBody<T>(create(SystemCode.SUCCESS, message), t);
  }


  public static <T> ResponseBody<T> error() {
    return new ResponseBody<T>(create(SystemCode.ERROR), null);
  }

  public static <T> ResponseBody<T> error(String message) {
    return errorMessage(message, null);
  }

  public static <T> ResponseBody<T> error(StatusCode<String> code) {
    return errorMessage(code, null, null);
  }


  public static <T> ResponseBody<T> error(StatusCode<String> code, String message) {
    return errorMessage(code, message, null);
  }


  public static <K, T> ResponseBody<T> errorMessage(StatusCode<String> code, String message, T t) {
    return new ResponseBody<T>(create(code, message), t);
  }

  public static <T> ResponseBody<T> errorMessage(String message, T t) {
    return new ResponseBody<T>(create(SystemCode.ERROR, message), t);
  }


  private static <K> ResponseHeader<K> create(StatusCode<K> code) {
    return create(code, null);
  }

  private static <K> ResponseHeader<K> create(StatusCode<K> code, final String specificMessage) {
    // TODO: @peikunkun 2021/1/6 0006 请求主键id,这里先不做实现
    return new ResponseHeader<K>(String.valueOf(System.currentTimeMillis()), code.getCode(),
        Optional.ofNullable(specificMessage).orElse(code.getMessage()), "default");
  }
}
